package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.pojo.Category;
import com.itheima.goods.service.CategoryService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
@CrossOrigin
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @GetMapping()
    public Result findAll() {
        List<Category> list = categoryService.list();
        return new Result(true, StatusCode.OK, "查询成功", list);
    }

    @PostMapping()
    public Result add(@RequestBody Category category) {
        categoryService.save(category);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @GetMapping("/search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size) {
        Page<Category> pages = categoryService.page(new Page<Category>(page, size));
        PageResult<Category> categoryPageResult = new PageResult<>();
        categoryPageResult.setTotal(pages.getTotal());
        categoryPageResult.setRows(pages.getRecords());
        return new Result(true, StatusCode.OK, "查询成功", categoryPageResult);
    }

    @PostMapping("/search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size,
                           @RequestBody Map searchMap) {

        PageResult pageResult = categoryService.findPage(page, size, searchMap);
        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        Category category = categoryService.getById(id);
        return new Result(true, StatusCode.OK, "查询成功", category);
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Integer id,
                         @RequestBody Category category) {
        LambdaQueryWrapper<Category> wrapper = Wrappers.<Category>lambdaQuery();
        wrapper.eq(Category::getId, id);
        categoryService.update(category, wrapper);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        categoryService.removeById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }
}
